package com.zhongkun.datahome.service.res.house;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.zhongkun.datahome.common.utils.bean.BeanUtils;
import com.zhongkun.datahome.service.constant.NodeStatusEnum;
import com.zhongkun.datahome.service.domain.CustomerHouse;
import com.zhongkun.datahome.service.domain.HouseBuildPlan;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @Author: lifengsheng
 * @Date: 2025/5/7 11:46
 * @Desc
 */
@Data
public class CustomerHouseAppVo extends CustomerHouse {
    @ApiModelProperty("房产施工计划")
    private List<HouseBuildPlan> houseBuildPlanList;

    @ApiModelProperty("当前阶段")
    private String currentStage;

    @JsonFormat(pattern = "yyyy-MM-dd")
    @ApiModelProperty("计划完成时间")
    private Date planCompleteDate;

    public static CustomerHouseAppVo of(CustomerHouse customerHouse, List<HouseBuildPlan> houseBuildPlanList) {
        CustomerHouseAppVo customerHouseAppVo = new CustomerHouseAppVo();
        BeanUtils.copyBeanProp(customerHouseAppVo, customerHouse);

        // 节点正序排序
        houseBuildPlanList.sort(Comparator.comparing(HouseBuildPlan::getBeginDate, Comparator.nullsLast((Comparator.naturalOrder()))));
        customerHouseAppVo.setHouseBuildPlanList(houseBuildPlanList);

        // 当前阶段
        houseBuildPlanList.stream()
                .filter(item -> NodeStatusEnum.NOT_COMPLETE.is(item.getNodeStatus()))
                .findFirst()
                .ifPresent(item -> {
                    customerHouseAppVo.setCurrentStage(item.getNodeName());
                    customerHouseAppVo.setPlanCompleteDate(item.getBeginDate());
                });

        // 所有阶段已完成，取最后一个阶段
        if (StringUtils.isBlank(customerHouseAppVo.getCurrentStage()) && CollectionUtils.isNotEmpty(houseBuildPlanList)) {
            //customerHouseAppVo.setCurrentStage("竣工");
            HouseBuildPlan lastPlan = houseBuildPlanList.get(houseBuildPlanList.size() - 1);
            customerHouseAppVo.setCurrentStage(lastPlan.getNodeName());
            customerHouseAppVo.setPlanCompleteDate(lastPlan.getBeginDate());
        }
        return customerHouseAppVo;
    }
}
